<!--
 * @Description: 底部购物结算
 * @Author: Kerwin
 * @Date: 2025-05-12 17:14:40
 * @LastEditTime: 2025-11-03 14:54:42
 * @LastEditors:  Please set LastEditors
-->

<!-- components/GoodsCard.vue -->
<template>
  <view class="goods-card">
    <van-overlay
      v-if="chooseGoods.length > 0"
      :show="showBottom"
      @click="showBottom = false"
    >
      <view class="diaolog" v-if="chooseGoods.length > 0">
        <!-- 自定义弹出层 -->
        <view class="topDiaolog">
          <van-cell title="已选商品">
            <template #right-icon>
              <view @click="clearChooseGoods">
                <van-icon name="delete-o" />
                <text>清空购物车</text>
              </view>
            </template>
          </van-cell>
        </view>
        <scroll-view class="bootomDiaolog" scroll-y="true">
          <view
            class="chooseGoods"
            @click.stop
            v-for="(item, index) in chooseGoods"
            :key="item.time"
          >
            <div class="left">
              <van-image
                class="img"
                width="100rpx"
                height="100rpx"
                :src="item.productImg"
                mode="scaleToFill"
              />
              <view class="words">
                <view class="goodName">{{ item.productName }}</view>
                <view class="dec"
                  >{{
                    item.details && item.details.otherCheckStr
                      ? item.details.otherCheckStr
                      : '/'
                  }}
                </view>
                <view>￥{{ item.money }}</view>
              </view>
            </div>
            <div class="right">
              <van-stepper
                @change="updateCartItemQuantity(item)"
                min="0"
                style="margin-top: 20rpx; float: right; margin-right: 50rpx"
                v-model="item.num"
                theme="round"
                button-size="22"
                disable-input
              />
            </div>
          </view>
        </scroll-view>
      </view>
    </van-overlay>

    <view
      class="footer"
      :style="{ height: shopData.shopProductSkuId ? '240rpx' : '200rpx' }"
    >
      <!-- orderdetail里面的footer -->
      <view class="stepper" v-if="shopData.shopProductSkuId">
        <van-stepper
          min="1"
          style="margin-top: 20rpx; float: right; margin-right: 50rpx"
          v-model="goodsNum"
          theme="round"
          button-size="22"
          disable-input
        />
      </view>
      <!-- oreder里面的footer -->
      <div
        class="bootom"
        :style="{ height: shopData.shopProductSkuId ? '' : '100%' }"
      >
        <view @click="dialog">
          <van-badge v-if="chooseGoods.length != 0" :content="allNum" max="15">
            <van-image
              class="img"
              width="60rpx"
              height="60rpx"
              fit="contain"
              :src="shopIcn"
            />
          </van-badge>
          <van-image
            class="img"
            v-else
            width="60rpx"
            height="60rpx"
            fit="contain"
            :src="shopIcn"
          />
        </view>
        <view class="custom-price">
          <view>
            <text class="price-integer">￥{{ formatPrice(totalMoney) }}</text>
            <text class="original-price"
              >￥{{ formatPrice(totalOriginalMoney) }}
            </text>
            <!-- <view style="color: #e64340;">+{{ goodsItem?.userScoreMoney }}复来券</view> -->
            <view
              style="color: #e64340; display: flex; align-items: center"
              v-if="shopData.shopMode != 6"
            >
              <text> +{{ formatPrice(totalSaveMoney) }}</text>
              <text style="margin: 0 10rpx">
                <u-image
                  width="30rpx"
                  height="20rpx"
                  :src="quan1"
                  mode="scaleToFill"
              /></text>
            </view>
          </view>
          <view>
            <text class="textMonry"
              >为您节省{{ formatPrice(totalSaveMoney) }}元</text
            >
          </view>
        </view>

        <view>
          <u-button
            :disabled="disabledBtn"
            class="custom-style"
            shape="circle"
            @click="onSubmit"
          >
            {{ textEnd }}</u-button
          >
        </view>
      </div>
    </view>
  </view>
</template>

<script setup lang="ts">
import {
  onReady,
  onShow,
  onLoad,
  onReachBottom,
  onPageScroll,
  onShareAppMessage,
  onPullDownRefresh
} from '@dcloudio/uni-app'
import { computed, reactive, ref, watch, onMounted } from 'vue'
// #region ***************** api *************************/
import { productApi, orderApi, moneyApi, enumAll } from '@/api'
//图片
import shopIcn from '@/static/xfl/shopIcn2.png'
import quan1 from '@/static/xfl/quan1.png'

//工具
import { useGoodStore, useUserStore, useCartStore } from '@/store'

//传参
const props = defineProps({
  shopData: {
    type: Object,
    default: () => {
      return { shopProductSkuId: '' }
    }
  },
  goodsItem: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

//初始数据
// const shopMode = ref(uni.getStorageSync('shopMode'))
const goodStore = useGoodStore()
const carStore = useCartStore()
const userStore = useUserStore()
const chooseGoods = computed(() => carStore.goodsList)
const flqTicket = ref(0) //复来券
const hlhyTicket = ref(0) //花积分抵用券
const clTicket = ref(0) //现金抵用券
const showBottom = ref(false) //当前选中
const goodsNum = ref(1)
const orderData = ref<any>({})
const textEnd = ref('立即结算')
const goodsItem = ref<any>({})
const shopData = ref<any>({})
const goodsList = ref<any>([])
const disabledBtn = ref(false) //提交按钮
// #region ***************** shopData *************************/
//监听选中的商品
watch(
  () => shopData.value,
  (newData) => {
    // 按钮
    if (newData.shopProductSkuId) {
      textEnd.value = '加入购物车'
    } else {
      textEnd.value = '立即结算'
    }
  },
  { deep: true, immediate: true }
)

// watch(
//   () =>  goodsItem.value,
//   (newData) => {
//     //商品初始值
//     goodsList.value.push(newData)
//     console.log('选中商品==>',goodsList.value);

//   },
//   { deep: true, immediate: true }
// )

watch(
  () => props.goodsItem,
  (newData) => {
    //商品初始值
    goodsItem.value = { ...newData }
    goodsItem.value.num = goodsNum.value //1
    // newData.num = goodsNum.value // 1
    goodsList.value.push(newData)
  },
  { deep: true, immediate: true }
)

// watch(
//   () => chooseGoods.value,
//   (newData) => {
//     console.log('store==>', newData);
//     if (newData.length > 0) {
//        newData.forEach(item => {
//         console.log('changloskaol;', item, '产品');
//         if (item.shopProductSkuId == props.shopData.shopProductSkuId) {
//           goodsNum.value = item.num
//         }
//       })
//     }
//   },
//   { deep: true, immediate: true }
// )

// #region ***************** 增减数量 *************************/

//监听数量
watch(
  () => goodsNum.value,
  (newValue, oldValue) => {
    if (newValue == 0) {
      textEnd.value = '返回选择'
    } else {
      changeNum(newValue)

      textEnd.value = '加入购物车'
    }
  }
)

const changeNum = (num: any) => {
  goodsItem.value.num = num
}

// const changeNum = () => {
//   const newItem = { ...goodsItem.value, num: goodsNum.value }

//   // 判断是否已存在该商品
//   const existingIndex = goodStore.goodsList.findIndex(
//     item => item.shopProductSkuId === newItem.shopProductSkuId
//   )

//   if (existingIndex !== -1) {
//     // 已存在 → 替换整个对象（确保响应性）
//     goodStore.goodsList.splice(existingIndex, 1, newItem)
//   } else {
//     // 不存在 → 添加新商品
//     goodStore.addGoods(newItem)
//   }
// }

// #region ***************** 弹窗 *************************/
//打开弹窗
const dialog = () => {
  showBottom.value = !showBottom.value
}

//清空购物车
const clearChooseGoods = () => {
  carStore.clearGoods() // 直接调用 store 方法清空
  showBottom.value = false
}
//增减数量
const updateCartItemQuantity = (item: any) => {
  // debugger
  if (item.num === 0) {
    carStore.reduceGoods(item)
  }
  if (chooseGoods.value.length === 0) {
    showBottom.value = false
  }
}

//#endregion

// #region ***************** 获取商品信息 *************************/

// 获取商品数量
const getNumById = (id: number) => {
  const found = chooseGoods.value.find((good: any) => good.productId === id)
  return found ? found.num : 0
}
//商品总金额
const totalMoney = computed(() => {
  // 所有金额转成分进行整数运算
  const totalCents = chooseGoods.value.reduce((sum: number, item: any) => {
    let itemPrice = 0
    // 根据品牌不同计算小料不同

    if (
      item.details &&
      Array.isArray(item.details.otherStr) &&
      item.details.otherStr.length > 0
    ) {
      itemPrice = item.details.otherStr.reduce((acc: number, detail: any) => {
        return acc + (detail.price || 0)
      }, 0)
    } else if (
      item.details &&
      item.details.otherStr &&
      Array.isArray(item.details.otherStr.spu_specs) &&
      item.details.otherStr.spu_specs.length > 0
    ) {
      //奈雪的茶的价格计算

      itemPrice = item.details.otherStr.spu_specs.reduce(
        (acc: number, detail: any) => {
          return acc + (detail.price || 0)
        },
        0
      )
    } else {
      itemPrice = 0
    }
    let money = item.money + itemPrice
    return sum + money * item.num * 100
  }, 0)
  const saveCents = Math.round(totalSaveMoney.value * 100) // 将 totalSaveMoney 转为分

  const finalCents = Math.max(0, totalCents - saveCents) // 防止负数

  return finalCents / 100 // 转回元
})
//商品原价
const totalOriginalMoney = computed(() => {
  return chooseGoods.value.reduce(
    (sum: any, item: any) => sum + item.money * item.num,
    0
  )
})
//商品节省复来券
const totalSaveMoney = computed(() => {
  // 计算出产品总抵扣复来券
  let totalDeduction = chooseGoods.value.reduce(
    (sum: any, item: any) => sum + item.highestScoreMoney * item.num,
    0
  )
  // 根据当前模式使用对应的券金额
  const ticketValue = availableTicket.value

  if (Number(formatPrice(ticketValue)) >= totalDeduction) {
    return totalDeduction
  } else {
    return Number(formatPrice(ticketValue))
  }
})

//商品总数量
const allNum = computed(() => {
  return chooseGoods.value.reduce((sum: any, item: any) => sum + item.num, 0)
})
watch(
  () => allNum.value,
  (newValue, oldValue) => {
    console.log('allNum==>', newValue)
    if (newValue > 16) {
      uni.showToast({
        title: '购物车里的商品数量不能超过15个',
        icon: 'none',
        mask: true,
        duration: 3000
      })
      disabledBtn.value = true
    } else {
      disabledBtn.value = false
    }
  },
  { immediate: true }
)

// 格式化金额为两位小数
function formatPrice(value: number): string {
  const factor = 100
  const cents = Math.round(value * factor) // 四舍五入处理
  return (cents / factor).toFixed(2)
}

// 格式化金额为两位小数（不四舍五入）
function slicePrice(value: number, truncate = true): string {
  let num: number

  if (truncate) {
    const factor = 100
    num = Math.floor(value * factor) / factor // 截断逻辑
  } else {
    num = value // 或者保留原值
  }

  return num.toFixed(2) // 转成字符串格式 "xx.xx"
}

// #endregion

// #region ***************** 优惠计算 ************************* /
const getDiscountTicket = async () => {
  console.log('获取优惠券', shopData.value)

  try {
    if (shopData.value.shopMode == 1) {
      // 花积分模式
      const { data } = await moneyApi.getMemberSomeWalletMoney({
        walletRule: enumAll.wallet_rule_id_enum.花积分钱包
      })
      hlhyTicket.value = data
      flqTicket.value = 0
      clTicket.value = 0
    } else if (shopData.value.shopMode == 4) {
      // 复来券模式
      const { data } = await moneyApi.getMemberTotalFulaiquan()
      flqTicket.value = data
      hlhyTicket.value = 0
      clTicket.value = 0
    } else if (shopData.value.shopMode == 6) {
      // 长来模式
      const { data } = await moneyApi.getMemberSomeWalletMoney({
        walletRule: enumAll.wallet_rule_id_enum.现金抵用券
      })
      clTicket.value = data
      // console.log(data, '用户拥有的总的现金抵用券')
      hlhyTicket.value = 0
      flqTicket.value = 0
    }
  } catch (error) {
    console.error('获取优惠券失败:', error)
    flqTicket.value = 0
    hlhyTicket.value = 0
    clTicket.value = 0
  }
}

// 计算当前可用的优惠券金额
const availableTicket = computed(() => {
  switch (shopData.value.shopMode) {
    case '1':
      return hlhyTicket.value
    case '4':
      return flqTicket.value
    case '6':
      return clTicket.value
    default:
      return 0
  }
})
// #endregion

// #region ***************** 订单 *************************/
const getOrderMoney = async () => {
  let orderProductSkus = chooseGoods.value.map((item) => {
    item.count = item.num
    return item
  })
  orderData.value.orderProductSkus = orderProductSkus
  orderData.value.status = 0
  orderData.value.scoreMoney = 0

  const { data } = await orderApi.orderMoney(orderData.value)
  console.log(data, '复来券')
}

// #endregion

//加入购物车
const onSubmit = async () => {
  console.log('点击加入')
  // getOrderMoney()
  // debugger

  // await getOrderMoney()
  // creatOrder()
  switch (textEnd.value) {
    case '立即结算':
      uni.navigateTo({
        url: `/pages/bigLife/payMoney?restaurantId=${shopData.value.shopId}&shopBrandId=${shopData.value.brandId}&shopMode=${shopData.value.shopMode}`
      })
      break
    default:
      if (goodsNum.value == 0) {
        carStore.reduceGoods({ ...goodsItem.value })
        //返回
        uni.navigateBack()
      } else {
        // debugger
        carStore.addGoods({ ...goodsItem.value })
        //返回

        uni.navigateBack()
      }
      break
  }
}

onLoad((option: any) => {
  shopData.value = option
  getDiscountTicket()
})
</script>
<style lang="scss" scoped>
.goods-card {
  position: fixed;
  bottom: 0rpx;
  width: 100%;
  // height: 130rpx;
  padding: 20rpx 0;
  background-color: #fff;
  box-shadow: 16rpx -38rpx 100rpx 0rpx rgba(0, 0, 0, 0.07);

  .diaolog {
    position: fixed;
    bottom: 165rpx;
    // height: 300rpx;
    width: 100%;

    background-color: #fff;

    .bootomDiaolog {
      min-height: 300rpx;
      max-height: 800rpx;
      margin-bottom: 70rpx;
      // overflow: hidden;
      // overflow-y: auto;

      .chooseGoods {
        padding: 20rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-top: 2rpx solid #efeef2;

        .left {
          display: flex;
          justify-content: start;
          width: 60%;

          .img {
            // width: 100rpx;
            margin-right: 40rpx;
          }

          .words {
            width: calc(100% - 180rpx);

            .dec {
              color: #999;
              font-size: 24rpx;
            }

            .goodName {
              //    flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }

        .right {
          flex: 1;
        }
      }
    }
  }

  // .footer {
  //   .custom-price {
  //     display: flex;
  //     justify-content: space-between;
  //     align-items: center;
  //     height: 100rpx;
  //     width: 100%;
  //     // align-items: baseline; // 使用 baseline 对齐，使整数和小数部分垂直对齐
  //     font-size: 24rpx;
  //     // margin-bottom: 50rpx;
  //     // margin: 0 50rpx;
  //     // margin-left: 100rpx;

  //     .price-integer {
  //       color: #e64340;
  //       font-weight: bold;
  //       font-size: 36rpx; // 整数部分字体更大
  //       margin-right: 8rpx; // 调整间距，使 . 和小数部分紧贴
  //     }

  //     .price-decimal {
  //       color: #e64340;
  //       font-size: 24rpx; // 小数部分字体正常大小
  //       margin-left: -8rpx; // 调整间距，使 . 和小数部分紧贴
  //     }

  //     .original-price {
  //       color: #999;
  //       text-decoration: line-through;
  //       margin: 0 10rpx; // 原价与现价之间的间距
  //     }
  //   }

  //   .textMonry {
  //     margin-right: 30rpx;
  //     font-size: 24rpx;
  //     color: #e0a66c;
  //   }

  // }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    // height: 240rpx;
    height: 200rpx;
    background-color: #fff;
    box-shadow: 16rpx -38rpx 100rpx 0rpx rgba(0, 0, 0, 0.07);

    .stepper {
      height: 80rpx;
      background-color: #fff;
    }

    .bootom {
      padding: 0 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      // height: 100%; // 确保占满父容器高度

      .custom-price {
        // display: flex;
        height: 100rpx;
        // align-items: baseline; // 使用 baseline 对齐，使整数和小数部分垂直对齐
        font-size: 24rpx;
        // margin: 0 50rpx;
        // margin-left: 150rpx;

        .price-integer {
          color: #e64340;
          font-weight: bold;
          font-size: 36rpx; // 整数部分字体更大
          margin-right: 8rpx; // 调整间距，使 . 和小数部分紧贴
        }

        .price-decimal {
          color: #e64340;
          font-size: 24rpx; // 小数部分字体正常大小
          margin-left: -8rpx; // 调整间距，使 . 和小数部分紧贴
        }

        .original-price {
          color: #999;
          text-decoration: line-through;
          margin: 0 10rpx; // 原价与现价之间的间距
        }
      }

      .custom-style {
        color: #fff;
        background-color: #ff6c18;
      }

      .textMonry {
        margin-right: 30rpx;
        font-size: 24rpx;
        color: #e0a66c;
      }
    }
  }
}

:deep(.van-overlay) {
  height: 85%;
}
</style>
